//
//  AppDelegate.swift
//  Employee
//
//  Created by swordjoy on 2017/3/9.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import IQKeyboardManager
import UserNotifications
import AdSupport
import Moya

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
  //appStoreId = 1230035256
    var window: UIWindow?

    fileprivate var isUpload = false

    fileprivate var cancles:[String: Cancellable] = [:]
  
    fileprivate let reachability: Reachability = Reachability(hostName: GlobalConfig.BASE_OUT_URL)
    
    func observerNetworkStatus() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChange), name: Notification.Name.init("kNetworkReachabilityChangedNotification"), object: nil)
    
        reachability.startNotifier()
    }
    
  
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
        // 极光推送
        registerJSPush(launchOptions: launchOptions)
        // 环信
        //registerHuanXin()
        // IQ键盘管理
        IQConfig()
        // 百度统计
        baiduMobStatConfig()
    
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        let mainVC = MainTabBarC()
        window?.rootViewController = mainVC
        window?.makeKeyAndVisible()
    
        // 位置不能改变
        appStartWithNotice(launchOptions: launchOptions)
    
        observerNetworkStatus()//监听网络变化
    
        return true
    }


    // APP进入后台
    func applicationDidEnterBackground(_ application: UIApplication) {
  
        // 环信
        //EMClient.shared().applicationDidEnterBackground(application)
    }

    // APP即将进入前台
    func applicationWillEnterForeground(_ application: UIApplication) {
        
        networkStatusChange()
        
        // 环信
       // EMClient.shared().applicationWillEnterForeground(application)
        JPUSHService.resetBadge()
        application.applicationIconBadgeNumber = 0

    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        
        //runInBackground { ConversationHelper.unreadMessageCount() }
    }

    func applicationWillTerminate(_ application: UIApplication) { }
}

///MARK:离线上传抄表记录
extension AppDelegate {
    
    @objc func networkStatusChange() {
        
        print("网络变化了哟",reachability.currentReachabilityStatus())
        //开启网络会多次调用
        for (_,item) in cancles.enumerated() {
            guard !item.value.isCancelled else {
                continue
            }
            item.value.cancel()//网络变化时取消
        }
        cancles.removeAll()//
        
        guard reachability.currentReachabilityStatus().rawValue != 0 else {
            return
        }
        
    
        let queue = DispatchQueue(label: "autoUplaodReadMeterRecord")
        
        queue.async {
            self.autoUplaodReadMeterRecord()//上传离线抄表记录
        }
 
    }
    
    func autoUplaodReadMeterRecord() {
        
        
     let data = OffLineUploadReadMeterRecordHelper.shared.getRecord()
        guard data.count > 0 else {
            self.isUpload = false
            return
        }
        
        let group = DispatchGroup.init() //
        let queue = DispatchQueue.init(label: "OffLineUploadReadMeterRecord.appdelegate")
        
        for idx in 0..<data.count {
        
            queue.async(group: group, qos: .default, flags: [], execute: {
                self.upload(data[idx])
            })

        }
        
        group.notify(queue: queue) {//
            //
            NotificationCenter.default.post(name: NSNotification.Name.offLine.updateReadingTask, object: nil)
        }
        
        
    }
    
    func upload(_ params:[Any]) {
        
        var send = ReadingMeterDetailSubmitSend()
        
        send.taskId = params[0] as! String
        
        send.meterRead = params[1] as! String
        
        
        
        guard let images = params.last as? [UIImage] else {
            let cancel = self.submitReadingMeterTaskDetail(send)
            self.cancles[send.taskId] = cancel //保存cancle
            return
        }
        guard images.count > 0 else {
            let cancel = self.submitReadingMeterTaskDetail(send)
            self.cancles[send.taskId] = cancel //保存cancle
            return
        }
        
        var tempDatas: [Data] = []
        
        for uploadImage in images {
            tempDatas.append(uploadImage.uploadData)
        }
        
        
        let _ = FileRequest.shared.uploadImages(datas: tempDatas, progressClosure: { (progress) in
        }) { (ids) in
            
            var imageIds = ""
            
            for item in ids {
                imageIds += item.fileId + ","
            }
            imageIds.removeLast()
            send.fileIds = imageIds
            //
          let cancel = self.submitReadingMeterTaskDetail(send)
            self.cancles[send.taskId] = cancel //保存cancle
        }
        
        
      
        
    }
    
    
    func submitReadingMeterTaskDetail(_ send:ReadingMeterDetailSubmitSend ) -> Cancellable {
        
       let cancel = MeterRequest.shared.submitReadingMeterTaskDetail(send: send, success: {
            //上传成功后删除本地数据库对应得数据
            let _ = OffLineUploadReadMeterRecordHelper.shared.delete(with: send.taskId)
        }) {
            //上传失败也删除本地数据库对应得数据
            let _ = OffLineUploadReadMeterRecordHelper.shared.delete(with: send.taskId)
        }
        
        return cancel
    }
    
    
}


// MARK: - 环信

extension AppDelegate {
  
  func registerHuanXin() {
    
  }
  
}

// MARK: - JSPush

extension AppDelegate: JPUSHRegisterDelegate {
  
    /// app关闭后,点击通知进入
    fileprivate func appStartWithNotice(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        if let temp = launchOptions {
            let notification = temp[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
            
            guard let temp = notification else { return }
            
            guard let keys = temp.allKeys as? [String] else { return }
            
            guard let mainVC = SJApp.keyWindow.rootViewController as? MainTabBarC else {
                return
            }
            
            // 来自我们自己服务器
            if keys.contains("messageType") {
                let string = temp.object(forKey: "messageType") as! String
                // 如果来自工单和巡检,不做处理进入首页
                if "WorkOrder" == string {
                    
                    let dic = ["extras":temp]
                    handlePush(msgInfo: dic,isLaunch: true)
                
                } else if "InspectionTask" == string || "Meter" == string {
                    
                }
                // 如果来自通知消息
                else if "NewMessage" == string {
                    mainVC.selectedIndex = 2
                    let nav = mainVC.viewControllers?[2]
                    let noticeVC = NoticeVC()
                    if let nav = nav as? SJBaseNavigationC {
                        nav.pushViewController(noticeVC, animated: true)
                    }
                }
            }
            // 来自环信聊天
            else {
                mainVC.selectedIndex = 2
            }
        }
    }
    
  fileprivate func toHome() {
    let tabbar = SJApp.keyWindow.rootViewController as! MainTabBarC
    // 获取当前根 TabBar 控制器的当前选中子Nav视图
    let subNav = tabbar.viewControllers?[tabbar.selectedIndex]
    // 如果就是首页
    
    // 让当前控制器的选中子Nav视图回到根界面
    let _ = (subNav as! SJBaseNavigationC).popToRootViewController(animated: false)
    // 跳转首页
    tabbar.selectedIndex = 0
  }
  
  fileprivate func toNotice(){
    let tabbar = SJApp.keyWindow.rootViewController as! MainTabBarC
    let subNav = tabbar.viewControllers?[tabbar.selectedIndex]
    // 如果就是通知界面
    if (subNav as! SJBaseNavigationC).visibleViewController!.isKind(of: NoticeVC.self) { return }
    let _ = (subNav as! SJBaseNavigationC).popToRootViewController(animated: false)
    tabbar.selectedIndex = 2
    let twoNav = tabbar.viewControllers?[2]
    let notice = NoticeVC()
    (twoNav as! SJBaseNavigationC).pushViewController(notice, animated: true)
  }
  
  fileprivate func toMessasge() {
    let tabbar = SJApp.keyWindow.rootViewController as! MainTabBarC
    let subNav = tabbar.viewControllers?[tabbar.selectedIndex]
    // 如果就是通知界面
   
    let _ = (subNav as! SJBaseNavigationC).popToRootViewController(animated: false)
    tabbar.selectedIndex = 2
  }
  
  @available(iOS 10.0, *)
  func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {//后台点击响应
    let info = response.notification.request.content.userInfo
    
    let messageType = (info["messageType"] as? String) ?? ""
    let workOrderId = (info["workOrderId"] as? String) ?? ""
    let workOrderStatus = (info["workOrderStatus"] as? String) ?? ""
    
    
    let dic:[String: Any] = [
        "extras":[
        "messageType":messageType,
        "workOrderId":workOrderId,
        "workOrderStatus":workOrderStatus,
        ]
    ]
    
    /*
    switch UIApplication.shared.applicationState {
    case .background: break
//      if "InspectionTask" == messageType || "WorkOrder" == messageType { toHome() }
//      else if "NewMessage" == messageType { toNotice() }
    case .active: break
    case .inactive:
      if "InspectionTask" == messageType || "WorkOrder" == messageType || "Meter" == messageType { toHome() }
      else if "NewMessage" == messageType { toNotice() }
      else { toMessasge() }
    }
    */
    
    handlePush(msgInfo: dic)
    
    completionHandler()
    
    SJApp.log("didReceive")
  }
  
  @available(iOS 10.0, *)
  func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {////前台收到消息
    let info = notification.request.content.userInfo
    SJApp.log(info["messageType"] ?? "")
    SJApp.log("willPresent")
    completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
  }

  
    func registerJSPush(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        let entity = JPUSHRegisterEntity()
        
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        
        JPUSHService.setup(
            withOption: launchOptions,
            appKey: GlobalConfig.JSPush_Key,
            channel:"App Store",
            apsForProduction: !SJToolkitConfig.serviceType)

        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(didReceiveMessageNotification(_:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(didLogin), name: NSNotification.Name.jpfNetworkDidLogin, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(didRegister), name: NSNotification.Name.jpfNetworkDidRegister, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(isConnecting), name: NSNotification.Name.jpfNetworkIsConnecting, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(isConnecting), name: NSNotification.Name.jpfServiceError, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(failedRegister), name: NSNotification.Name.jpfNetworkFailedRegister, object: nil)
        JPUSHService.setDebugMode()
    }
  
  @objc func didReceiveMessageNotification(_ notification: Notification) {
    SJApp.log("didReceiveMessageNotification" + "\(JPUSHService.registrationID())")
    let userInfo = notification.userInfo! as NSDictionary
    
    print("收到通知了,userInfo=",userInfo)
    
    handlePush(msgInfo: userInfo as! [String : Any])
    
    /*
    let allKeys = userInfo.allKeys as! [String]
    if allKeys.contains("extras") {
      let dic = userInfo.object(forKey: "extras") as! NSDictionary
      let subAllKeys = dic.allKeys as! [String]
        SJApp.log(subAllKeys)
      if subAllKeys.contains("messageType") {
        let type = dic.object(forKey: "messageType") as! String
        SJApp.log(type)
        if type == "NewMessage" {
            Account.isNotice = true
            GlobalConfig.notificationCenter.post(name: Notification.Name.hxMessage.updateUnreadMessageCount, object: nil)
            GlobalConfig.notificationCenter.post(name: Notification.Name.hxMessage.updateMessageVCNotice, object: nil)
        }
        else if type == "WorkOrder" {
            GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeOrderData, object: nil, userInfo: ["pushData":dic])
        }
        else if type == "InspectionTask" {
            GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeInspectionData, object: nil)
        }
        else if type == "Meter" {
            GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeMeterData, object: nil)
        }
        else {
        
        }
      }
    }
    */
  }
    
    @objc func errorOccur() {
        SJApp.log("errorOccur:" + "\(JPUSHService.registrationID())")
    }
    
    @objc func failedRegister() {
        SJApp.log("failedRegister:" + "\(JPUSHService.registrationID())")
    }
    
    @objc func isConnecting() {
        SJApp.log("isConnecting" + "\(JPUSHService.registrationID())")
    }
    @objc func didSetup() {
        SJApp.log("didSetup" + "\(JPUSHService.registrationID())")
    }
    @objc func didRegister() {
        SJApp.log("didRegister" + "\(JPUSHService.registrationID())")
    }
    @objc func didLogin() {
        if Account.isLogin && !Account.isSetPushAlias { UserRequest.shared.setPushAlias() }
    }
}

// MARK: - UNUserNotificationCenterDelegate iOS 10 和通知推送相关
extension AppDelegate: UNUserNotificationCenterDelegate {
  
  // 推送的设备token
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // 将token传送给环信
    //let _ = EMClient.shared().bindDeviceToken(deviceToken)
    JPUSHService.registerDeviceToken(deviceToken)
  }
  
  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    SJApp.log("注册deviceToken失败")
  }
  
  
  // 接收到本地通知
  func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    
  }
  
  // 接收到远程通知
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

    //EaseSDKHelper.share().hyphenateApplication(UIApplication.shared, didReceiveRemoteNotification: userInfo)
    JPUSHService.handleRemoteNotification(userInfo)
  
    /*
    switch application.applicationState {
    case .active: break
    case .background: break
//      if "InspectionTask" == messageType || "WorkOrder" == messageType { toHome() }
//      else if "NewMessage" == messageType { toNotice() }
    case .inactive:
      if "InspectionTask" == messageType || "WorkOrder" == messageType
      || "Meter" == messageType
      { toHome() }
      else if "NewMessage" == messageType { toNotice() }
      else { toMessasge() }
    }
 */
    let messageType = (userInfo["messageType"] as? String) ?? ""
    let workOrderId = (userInfo["workOrderId"] as? String) ?? ""
    let workOrderStatus = (userInfo["workOrderStatus"] as? String) ?? ""
    
    
    let dic:[String: Any] = [
        "extras":[
            "messageType":messageType,
            "workOrderId":workOrderId,
            "workOrderStatus":workOrderStatus,
        ]
    ]
    
    handlePush(msgInfo: dic)
    
  }
  
  @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
    SJApp.log("userNotificationCenter didReceive")
    SJApp.log(response.notification.request.content.userInfo)
    completionHandler()
  }
  
  @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
    //let userInfo = notification.request.content.userInfo
    //EaseSDKHelper.share().hyphenateApplication(UIApplication.shared, didReceiveRemoteNotification: userInfo)
  }
  
  
}

// MARK: - IQKeyboardManager

extension AppDelegate {
  
  fileprivate func IQConfig() {
    
    IQKeyboardManager.shared().isEnabled = true
    IQKeyboardManager.shared().shouldResignOnTouchOutside = true
    IQKeyboardManager.shared().isEnableAutoToolbar = true
    IQKeyboardManager.shared().toolbarTintColor = GlobalConfig.BGSkyBlueColor
    IQKeyboardManager.shared().toolbarDoneBarButtonItemText = "完成"
    IQKeyboardManager.shared().shouldShowToolbarPlaceholder = false
    
    UITextField.appearance().tintColor = GlobalConfig.BGSkyBlueColor
    UITextView.appearance().tintColor = GlobalConfig.BGSkyBlueColor
    
  }
  
}

// MARK: - 百度统计

extension AppDelegate {
  
  fileprivate func baiduMobStatConfig() {
    #if RELEASE
        BaiduMobStat.default().start(withAppId: "c0e255bae0")
        BaiduMobStat.default().enableDebugOn = false
    #endif
  }
  
}
///通知处理
extension AppDelegate {
    
    func handlePush(msgInfo:[String: Any],isLaunch: Bool = false) {
        
        if !isLaunch {
            if UIApplication.shared.applicationState == .active {
                return
            }
        }
        
        switch UIApplication.shared.applicationState {
        case .active:
            print("APP 状态","active")
        case .inactive:
            print("APP 状态","inactive")
        case .background:
            print("APP 状态","background")
        
        }
        
        
        guard let extras = msgInfo["extras"] as? [String: String] else {
            return
        }
        
        guard let type = extras["messageType"]  else {
            return
        }
        
        switch type {
        
        case "WorkOrder":
             GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeOrderData, object: nil, userInfo: ["pushData":extras])
            
        case "InspectionTask":
            GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeInspectionData, object: nil)
            
        case "Meter":
             GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeMeterData, object: nil)
        default:
            break
        }
        
    }
    
    
    
    
}


